package classroom;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import applicationDAO.InstituteDAO;

import com.project.trac.R;

import core.modules.DatabaseConnector;

public class FileBrowser extends InstituteDAO {

	TextView downloadedValue;

	ProgressBar progressBar;
	AlertDialog.Builder alertDialog;
	ProgressDialog progressDialog;
	
	String DOWNLOADPATH;
	String HEADER;
	String FILE;

	public static ListFragment newInstance(Context context) {
		FileBrowser lf = new FileBrowser();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		ViewGroup root = (ViewGroup) inflater.inflate(R.layout.generic_list_a, null);

		DatabaseConnector.setSubDirectory("Files");
		
		new AsynchronousTask().execute();
		
		return root;
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int pos, long id) {
		System.out.println(l.getItemAtPosition(pos));
		System.out.println(DOWNLOADPATH.replace(" ","_"));
		doDownload(DOWNLOADPATH.replace(" ","_"));
		showProgress(FILE);
	}
	
	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	// ---------------------------- * Downloader *
	
	private String doDownload(final String downloadPath) {
		
		Thread dx = new Thread() {

			int fileSize = 0;
			long downloaded = 0;

			public void run() {
				File root = android.os.Environment.getExternalStorageDirectory();
				File dir = new File(root.getAbsolutePath() + "/TRAC/" + HEADER + "/" );
				
				if (!dir.exists()) {
					dir.mkdirs();
					Log.w("Directory exists (After creation)", 
							String.valueOf(dir.exists()));
				}
				
				try {
					URL url = new URL(downloadPath);
					URLConnection connection = url.openConnection();
					connection.connect();

					fileSize = connection.getContentLength();
					getActivity().runOnUiThread(new Runnable() {
						public void run() {
							progressBar.setMax(fileSize);
						}
					});

					InputStream input = new BufferedInputStream(url.openStream());
					OutputStream output = new FileOutputStream(dir + "/" + FILE);

					byte bufferLength[] = new byte[1024];
					int received;

					while ((received = input.read(bufferLength)) != -1) {
						downloaded += received;
						output.write(bufferLength, 0, received);
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								progressBar.setProgress((int) downloaded);
								float per = (downloaded / (float) fileSize) * 100;
								downloadedValue.setText(downloaded
										+ "/" + fileSize + "KB (" + per + "%)");
								
								if ((downloaded/fileSize) == 1) {
									alertDialog.setNeutralButton("Done", new OnClickListener() {
										
										@Override
										public void onClick(DialogInterface dialog, int which) {
											dialog.dismiss();
										}
									});
								}
							}
						});
						
					}
					output.flush();
    				output.close();
    				input.close();

				} catch (FileNotFoundException e) {
					showError(e.getClass().toString());
				} catch (IOException e) {
					showError(e.getClass().toString());
				}
			}
		};

		dx.start();
		
		return FILE;

	}

	private void showProgress(String fileName) {

		alertDialog = new AlertDialog.Builder(getActivity());
		
		View view = View.inflate(getActivity(), R.layout.generic_progressbar, null);
		alertDialog.setView(view);
		alertDialog.setIcon(android.R.drawable.ic_dialog_info);
		alertDialog.setTitle("File Download");

		TextView text = (TextView) view.findViewById(R.id.fileName);
		text.setText(fileName);
		downloadedValue = (TextView) view.findViewById(R.id.download_progress);
		downloadedValue.setText("Starting download...");
		alertDialog.show();

		progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
		progressBar.setProgress(0);
		progressBar.setProgressDrawable(getResources().getDrawable(R.drawable.progressbar_state));
		
	}
	
	private void showError(final String err) {
		getActivity().runOnUiThread(new Runnable() {
			public void run() {
				Toast.makeText(getActivity(), err, Toast.LENGTH_LONG).show();
			}
		});
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ResultSet rs;
		
		ProgressDialog progressDialog;

		String KEY_DOC_NAME = "k1";
		String KEY_HEADER = "k2";


		protected void onPreExecute() {
			super.onPreExecute();

			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setIcon(android.R.drawable.ic_dialog_info);
			progressDialog.setMessage("Retrieving the file list, please wait.");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {
			
			try {
				rs = DatabaseConnector.getStatement().executeQuery(
						  " SELECT documents.name, curriculum.catalognumber"
						+ " FROM documents"
						+ " INNER JOIN curriculum on curriculum.id = documents.uploadto"
						+ " WHERE uploadto = " + getSubjectID()
						);
				
				while (rs.next()) {

					m = new HashMap<String, String>();
					m.put(KEY_DOC_NAME, rs.getString("name"));
					m.put(KEY_HEADER, rs.getString("catalognumber"));
					
					arrayList.add(m);
					
					FILE = rs.getString("name");
					HEADER = rs.getString("catalognumber");
					DOWNLOADPATH = DatabaseConnector.getRootDirectory().concat(rs.getString("catalognumber")) + 
							       DatabaseConnector.getSubDirectory() + rs.getString("name");
				}


			} catch (SQLException e) {
				Log(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			progressDialog.dismiss();

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					SimpleAdapter adapter = new SimpleAdapter(getActivity(), arrayList,
							R.layout.row_detail_documents, 
							new String[] {KEY_DOC_NAME}, 
							new int[] {R.id.header_docName });
					setListAdapter(adapter);

				}

			});
		}
	} 

}